package com.hhkj.api.course.service.biz.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hhkj.admin.course.domain.Course;
import com.hhkj.admin.course.domain.CoursePriceConf;
import com.hhkj.admin.course.service.base.CoursePriceConfService;
import com.hhkj.admin.course.service.biz.CourseBizService;
import com.hhkj.admin.course.service.biz.SaleCourseBizService;
import com.hhkj.api.course.service.biz.ApiSaleCourseBizService;
import com.ruoyi.common.cont.SysConst;
import com.ruoyi.common.exception.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * ApiSaleCourseBizServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/31 17:49
 */
@Service
public class ApiSaleCourseBizServiceImpl implements ApiSaleCourseBizService {

    @Autowired
    private CourseBizService courseBizService;
    @Autowired
    private SaleCourseBizService saleCourseBizService;
    @Autowired
    private CoursePriceConfService coursePriceConfService;

    @Override
    public List<Course> listFreePrice() {
        List<Course> courseList = saleCourseBizService.listFree();
        if (CollectionUtil.isEmpty(courseList)) {
            throw new GlobalException("暂无免费的课程信息");
        }
        return courseList;
    }

    @Override
    public List<Course> listSecondLevelTree() {
        List<Course> courseList = courseBizService.listNodeTreeAll();
        return courseList.stream()
                .filter(coursePo ->
                        coursePo.getLevelNum().equals(2)
                                && SysConst.Flag.NO.getFlag().equals(coursePo.getDisableFlag()))
                .collect(Collectors.toList());
    }

    @Override
    public List<Course> listSecondLevelTreePaid() {
        List<Course> courseList = listSecondLevelTree();
        // 获取免费的课程id信息列表
        LambdaQueryWrapper<CoursePriceConf> priceQueryWrapper = new LambdaQueryWrapper<>();
        priceQueryWrapper.le(CoursePriceConf::getPrice, BigDecimal.ZERO);
        List<CoursePriceConf> priceConfList = coursePriceConfService.list(priceQueryWrapper);
        if (CollectionUtil.isNotEmpty(priceConfList)) {
            Set<Long> freeCourseSet = priceConfList.stream()
                    .map(CoursePriceConf::getCourseId)
                    .collect(Collectors.toSet());
            return courseList.stream()
                    .filter(coursePo -> !freeCourseSet.contains(coursePo.getId()))
                    .collect(Collectors.toList());
        }
        return courseList;
    }


    @Override
    public List<Course> listCourseTreeAllList(List<Long> idList) {
        return courseBizService.allList(idList);
    }
}
